package com.ikingtech.platform.service.push.websocket.handler;

import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.push.websocket.session.WebsocketSessionManager;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import java.io.IOException;
import java.util.List;

/**
 * @author tie yan
 */
@Slf4j
@RequiredArgsConstructor
public class WebsocketHandler extends AbstractWebSocketHandler {

    private static final String SESSION_ATTRIBUTE_USER_ID = "userId";

    private final List<WebsocketMessageAnnouncer> announcers;

    /**
     * 建立连接
     * @param session 会话
     */
    @Override
    public void afterConnectionEstablished(@NonNull WebSocketSession session) throws IOException {
        String userId = (String) session.getAttributes().get(SESSION_ATTRIBUTE_USER_ID);
        session.sendMessage(new TextMessage(Tools.Str.format("[service-push][websocket][ws/message]user[{}] connected!", userId)));
        WebsocketSessionManager.add(userId, session);
    }

    @Override
    protected void handlePongMessage(@NonNull WebSocketSession session, @NonNull PongMessage message) throws IOException {
        session.sendMessage(new PingMessage());
    }

    @Override
    protected void handleTextMessage(@NonNull WebSocketSession session, @NonNull TextMessage message) {
        String userId = (String) session.getAttributes().get(SESSION_ATTRIBUTE_USER_ID);
        this.announcers.forEach(announcer -> announcer.broadcast(userId, message.getPayload()));
    }

    @Override
    public void handleTransportError(@NonNull WebSocketSession session, @NonNull Throwable exception) {
        WebsocketSessionManager.remove(session.getId());
    }

    @Override
    public void afterConnectionClosed(@NonNull WebSocketSession session, @NonNull CloseStatus closeStatus) {
        WebsocketSessionManager.remove(session.getId());
    }
}
